import { Upload, Modal, Input, message, Tooltip, Spin } from 'antd';
import { useModel } from 'umi';
import { useState, useEffect, useRef } from 'react';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import type { UploadChangeParam } from 'antd/es/upload';
import styles from './index.less';
import classNames from 'classnames';
import AuthModal, { AuthResult } from '../AuthModal';
import accountDefaultBg from '@/assets/pc/images/account/account-bg.jpeg';
import { allGet } from '@/services/pc';
import { apiUrl } from '@/common/const';
const isImg = (name) => {
  const arr = ['.jpg', '.jpeg', '.png', '.gif'];
  const index = name.lastIndexOf('.');
  const suffix = name.slice(index);
  return arr.includes(suffix);
};

interface UerInfoProps {
  edit?: boolean;
  userInfo: any;
  onRefreshInfo?: () => void;
}

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};
const UerInfo: React.FC<UerInfoProps> = ({ userInfo, edit = false, onRefreshInfo }) => {
  // 获取上传的hash配置
  const [config, setConfig] = useState<Record<string, any>>({});
  const init = async () => {
    const response = await allGet({ params: { mod: 'teacher', do: 'add', version: 'pc1.0' } });
    setConfig(response?.data?.swfconfig ?? {});
  };
  useEffect(() => {
    init();
  }, []);

  /**
   * 头像等信息
   */
  const { setUseInfo } = useModel('user');

  // 弹窗url
  const [imageUrl, setImageUrl] = useState<string>();
  useEffect(() => {
    if (imageUrl !== userInfo?.avatar) {
      setImageUrl(userInfo?.avatar);
    }
  }, [userInfo]);

  /**
   * 修改头像等
   */
  const beforeUpload = async (file) => {
    const isimg = isImg(file.name);
    // 格式不符合
    if (!isimg) {
      message.error('图片仅支持 jpg/png/gif 格式');
      return Upload.LIST_IGNORE;
    }

    return file;
  };

  // 编辑头像
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setAvatarUploading(true);
      return;
    }
    if (info.file.status === 'done') {
      setAvatarUploading(false);
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setImageUrl(url);
      });
    }
    if (info.file.status === 'error') {
      setAvatarUploading(false);
      message.error('上传失败');
    }
  };

  // 上传头像props
  const [avatarUploading, setAvatarUploading] = useState(false);
  const avatarUploadProps = {
    action: apiUrl,
    name: 'Filedata',
    showUploadList: false,
    data: {
      mod: 'swfupload',
      ac: 'avatar',
      uid: userInfo?.uid,
      hash: config?.hash,
      version: 'pc1.0',
    },
    beforeUpload,
    onChange: handleChange,
    maxCount: 1,
  };
  // 认证
  const handleAuth = () => {
    AuthModal.show({
      onSuccess: async (values, type) => {
        AuthResult.show({
          onClick: () => {},
        });
      },
    });
  };

  // 是否实名认证
  const isVerify = userInfo?.verify === 1;
  const bgUploadProps = {
    action: apiUrl,
    name: 'Filedata',
    className: styles.uploadVideo,
    showUploadList: false,
    data: {
      mod: 'swfupload',
      ac: 'profile',
      uid: userInfo?.uid,
      hash: config?.hash,
      field: 'spacebg',
      version: 'pc1.0',
    },
    maxCount: 1,
    beforeUpload: async (file) => {
      const isimg = isImg(file.name);
      // 格式不符合
      if (!isimg) {
        message.error('图片仅支持 jpg/png/gif 格式');
        return Upload.LIST_IGNORE;
      }

      message.loading('上传中');
      return file;
    },
    onChange: (info: UploadChangeParam<UploadFile>) => {
      if (info.file.status === 'done') {
        if (!info.file?.response?.success) {
          return message.error('上传失败');
        }
        getBase64(info.file.originFileObj as RcFile, (url) => {
          setUseInfo({ spacebg: url });
        });
        return;
      }
      if (info.file.status === 'error') {
        message.error('上传失败');
      }
      return;
    },
  };
  const accountBg = userInfo?.spacebg;
  //|| accountDefaultBg;

  useEffect(() => {
    sightmlRef.current = userInfo?.sightml;
  }, [userInfo?.sightml]);
  // 签名
  const sightmlRef = useRef('');
  const handleSightml = (e) => {
    sightmlRef.current = e.target.value;
  };

  /**
   * 编辑弹窗
   */
  const [editVisible, setEditVisible] = useState(false);
  const handleSave = async () => {
    await allGet({
      params: { mod: 'user', do: 'update', version: 'pc1.0', sightml: sightmlRef.current },
    });
    setUseInfo({
      avatar: imageUrl,
    });
    onRefreshInfo?.();
    setEditVisible(false);
  };

  const handleCancel = () => {
    setImageUrl(userInfo?.avatar);
    setEditVisible(false);
  };
  return (
    <div className={styles.userInfo}>
      <div className={styles.bg}>
        <div className={styles.ratio}>
          <div className={styles.content} style={{ backgroundImage: `url(${accountBg})` }}>
            <i className={styles.mask} />
            <div className={styles.main}>
              {edit && (
                <Upload {...bgUploadProps}>
                  <div className={styles.editbg}>
                    <i className={styles.icon} />
                    <div className={styles.text}>修改封面</div>
                  </div>
                </Upload>
              )}
              <div className={styles.info}>
                <div className={styles['avatar-wrapper']}>
                  <i
                    className={styles.avatar}
                    style={{ backgroundImage: `url(${userInfo?.avatar})` }}
                  />
                  {edit && (
                    <div className={styles.over}>
                      <i className={styles.mask} />
                      <div className={styles.text} onClick={() => setEditVisible(true)}>
                        编辑资料
                      </div>
                    </div>
                  )}
                </div>
              </div>
              <div className={styles.nick}>
                <span className={styles.text}>
                  {userInfo?.username}
                  <Tooltip title="已经实名认证">
                    {isVerify && (
                      <img
                        loading="lazy"
                        className={styles.icon}
                        src={require('@/assets/pc/images/account/icon-authed.png')}
                        alt=""
                      />
                    )}
                  </Tooltip>
                </span>
              </div>
              <p className={styles.sign}> {userInfo?.introduction || '你很懒哦，说点什么吧'} </p>
              {edit && !isVerify && (
                <div className={styles.auth} onClick={handleAuth}>
                  未实名，前往实名认证 <i className={styles.icon} />
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      <Modal
        destroyOnClose
        className={styles.editModal}
        visible={editVisible}
        width={390}
        footer={null}
        onCancel={handleCancel}
        maskClosable
      >
        <div className={styles.header}>
          <div className={styles.avatar} style={{ backgroundImage: `url(${imageUrl})` }}>
            {avatarUploading && (
              <>
                {' '}
                <i className={styles.mask} />
                <Spin className={styles.avatarUploading} />
              </>
            )}
          </div>

          <Upload {...avatarUploadProps}>
            <div className={styles.uploadAvatar}>修改头像</div>
          </Upload>
        </div>
        <div className={styles.title}>个性签名：</div>
        <Input.TextArea
          className={styles.textarea}
          placeholder="请输入"
          style={{ height: 140, backgroundColor: '#293E6B' }}
          defaultValue={userInfo?.sightml}
          onChange={handleSightml}
        />
        <div className={styles.footer}>
          <div className={classNames(styles.btn, styles.cancel)} onClick={handleCancel}>
            取消
          </div>
          <div className={styles.btn} onClick={handleSave}>
            确定
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default UerInfo;
